package org.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.order.entity.ShippingAddress;
import org.example.order.mapper.ShippingAddressMapper;
import org.example.order.service.ShippingAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class ShippingAddressServiceImpl extends ServiceImpl<ShippingAddressMapper, ShippingAddress> implements ShippingAddressService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShippingAddress add(ShippingAddress shippingAddress) {
        // 如果设置为默认地址，则将该用户的其他地址设为非默认
        if (shippingAddress.getIsDefault() == 1) {
            resetDefaultAddress(shippingAddress.getUserId());
        }

        // 插入新地址
        this.save(shippingAddress);

        return shippingAddress;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id, Long userId) {
        // 先查询是否存在该地址且属于该用户
        ShippingAddress address = getOne(new LambdaQueryWrapper<ShippingAddress>()
                .eq(ShippingAddress::getId, id)
                .eq(ShippingAddress::getUserId, userId));

        if (address == null) {
            return false;
        }

        // 删除地址
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAddress(ShippingAddress shippingAddress) {
        // 如果设置为默认地址，则将该用户的其他地址设为非默认
        if (shippingAddress.getIsDefault() == 1) {
            resetDefaultAddress(this.getById(shippingAddress.getId()).getUserId());
        }

        // 更新地址
        return updateById(shippingAddress);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefault(Long id, Long userId) {
        // 先查询是否存在该地址且属于该用户
        ShippingAddress address = getOne(new LambdaQueryWrapper<ShippingAddress>()
                .eq(ShippingAddress::getId, id)
                .eq(ShippingAddress::getUserId, userId));

        if (address == null) {
            return false;
        }

        // 重置该用户的默认地址
        resetDefaultAddress(userId);

        // 设置新的默认地址
        address.setIsDefault(1);
        return updateById(address);
    }

    @Override
    public List<ShippingAddress> listByUserId(Long userId) {
        return list(new LambdaQueryWrapper<ShippingAddress>()
                .eq(ShippingAddress::getUserId, userId)
                .orderByDesc(ShippingAddress::getIsDefault)
                .orderByDesc(ShippingAddress::getUpdateTime));
    }

    @Override
    public ShippingAddress getDefaultAddress(Long userId) {
        return getOne(new LambdaQueryWrapper<ShippingAddress>()
                .eq(ShippingAddress::getUserId, userId)
                .eq(ShippingAddress::getIsDefault, 1));
    }

    @Override
    public ShippingAddress getById(Long id, Long userId) {
        return getOne(new LambdaQueryWrapper<ShippingAddress>()
                .eq(ShippingAddress::getId, id)
                .eq(ShippingAddress::getUserId, userId));
    }

    /**
     * 重置用户的默认地址（将所有地址设为非默认）
     */
    private void resetDefaultAddress(Long userId) {
        update(new LambdaUpdateWrapper<ShippingAddress>()
                .eq(ShippingAddress::getUserId, userId)
                .eq(ShippingAddress::getIsDefault, 1)
                .set(ShippingAddress::getIsDefault, 0));
    }
}